﻿using System;
using System.Configuration;
using System.IO;
using System.Threading;

namespace LMSemir.Common
{
    /// <summary>
    /// 日志管理类
    /// </summary>
    public class LogUtil
    {
        #region 日志记录
        private static LogUtil _logger;
        private static readonly string LogFilePath = ConfigurationManager.AppSettings["logPath"];
        private static readonly Mutex Mutex = new Mutex(false);

        /// <summary>
        /// 单件
        /// </summary>
        /// <returns></returns>
        public static LogUtil GetInstance()
        {
            if (_logger == null)
            {
                _logger = new LogUtil();
                if (!Directory.Exists(LogFilePath))
                {
                    Directory.CreateDirectory(LogFilePath);
                }
            }
            return _logger;
        }

        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="message">The message.</param>
        public void WriteDebugLog(string message)
        {
            WriteLogFile(message);
        }

        /// <summary>
        /// 错误日志记录
        /// </summary>
        /// <param name="message">The message.</param>
        private static void WriteLogFile(string message)
        {
            try
            {
                Mutex.WaitOne();
                string strSysTime = DateTime.Now.ToString("yyyy-MM-dd");
                string logFullPath = LogFilePath + strSysTime + ".log";
                string logstr = message;

                if (!File.Exists(logFullPath))
                {
                    using (StreamWriter sw = File.CreateText(logFullPath))
                    {
                        sw.Write(logstr + "\r\n");
                        sw.Close();
                    }
                }
                else
                {
                    using (StreamWriter sw = File.AppendText(logFullPath))
                    {
                        sw.Write(logstr + "\r\n");
                        sw.Close();
                    }
                }
            }
            finally
            {
                Mutex.ReleaseMutex();
            }
        }
        #endregion
    }
}
